package com.justgame.project.base.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 异步线程池配置
 */
@Configuration
@EnableAsync
public class ThreadPoolConfig {

    /**
     * 每秒需要多少个线程处理
     * CPU线程数
     */
    private static final int corePoolSize = Runtime.getRuntime().availableProcessors();;


    /**
     * 线程池维护线程的最大数量
     * CPU线程数 * 2
     */
    private static final int maxPoolSize = corePoolSize * 2;

    /**
     * 缓存队列
     * CPU线程数 * 200
     */
    private static final int queueCapacity = maxPoolSize * 100;

    /**
     * 允许的空闲时间
     * 默认为60
     */
    private static final int keepAlive = 60;

    /**
     * 任务队列
     */
    private static final BlockingQueue<Runnable> QUEUE = new LinkedBlockingQueue<>(queueCapacity);

    /**
     * 计数器
     */
    private final static AtomicInteger COUNT = new AtomicInteger(0);

    @Bean(value = "taskExecutor",destroyMethod = "shutdown")
    public ThreadPoolExecutor taskExecutor() {
        return new ThreadPoolExecutor(
                corePoolSize,
                maxPoolSize,
                keepAlive,
                TimeUnit.SECONDS,
                QUEUE,
                new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
                        Thread thread = new Thread(
                                Thread.currentThread().getThreadGroup(),r,"pool-thread-" + COUNT.getAndDecrement(),0
                        );
                        thread.setDaemon(false);
                        return thread;
                    }
                },
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
    }

}
